<script setup>
import { onMounted, ref } from 'vue'
import { login, loginCode, loginCodePost, loginSocial, loginSocialComplement, registerCode, register } from '@/api/login'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useUserStore } from '@/stores'
const store = useUserStore()
const qqopenId = ref('')
const isqqLogin = ref('')
onMounted(() => {
  if (store.isLogined) {
    router.push('/')
    ElMessage.error('您已登录，请勿重复登录')
  }
  isqqLogin.value = window.QC.Login.check()
  console.log('isqqLogin', isqqLogin.value)
  // if (!isqqLogin.value) {
  //   return router.push('/login')
  // }

  window.QC.Login.getMe(async openId => {
    qqopenId.value = openId
    console.log('qqopenId', qqopenId.value)
    try {
      const res = await loginSocial(qqopenId.value)
      console.log('loginSocial', res)
      store.setUserInfo(res.data.result)
      ElMessage.success('登录成功')
      router.push('/')
    } catch {
      ElMessage.error('该QQ号未注册，请注册信息')
      toggleRegister()
    }
  })
  window.QC.api('get_user_info').success(res => {
    console.log('qquserInfo', res)
  })
})

// 控制账号登录或扫码登录的模式切换
const navChosen = ref(true)
const toggleModeAccount = () => {
  navChosen.value = true
  qrChosen.value = false
  registerShow.value = false
}
const qrChosen = ref(false)
const toggleModeQr = () => {
  navChosen.value = false
  qrChosen.value = true
  registerShow.value = false
}
const registerShow = ref(false)
const toggleRegister = () => {
  navChosen.value = false
  qrChosen.value = false
  registerShow.value = true
}

// 控制短信登录或账号登录的模式切换
const messageChosen = ref(true)
const toggleMode2 = () => {
  messageChosen.value = !messageChosen.value
}

// 登录表单-账号登录
const accountForm = ref({
  account: 'demo', // demo abcdef
  password: 'hm#qd@23!', // hm#qd@23! abcdefg
  aggrement: true
})
const validateAccept = (rule, value, callback) => {
  if (!value) {
    callback(new Error())
  } else {
    callback()
  }
}
const accountRules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 6, max: 24, message: '密码长度在 6 到 24 个字符', trigger: 'change' }
  ],
  aggrement: [{ validator: validateAccept, message: '请阅读并同意协议', trigger: 'change' }]
}

// 登录表单-短信登录
const messageForm = ref({
  mobile: '',
  code: '',
  aggrement: true
})
const messageRules = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'change' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'change' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'change' },
    { min: 6, max: 6, message: '验证码长度为 6 位', trigger: 'change' }
  ],
  aggrement: [{ validator: validateAccept, message: '请阅读并同意协议', trigger: 'change' }]
}

// 提交表单登录
const accountFormRef = ref(null)
const messageFormRef = ref(null)
const submit = () => {
  if (messageChosen.value) {
    // 账号登录
    accountFormRef.value.validate(async valid => {
      if (valid) {
        const res = await login(accountForm.value)
        store.setUserInfo(res.data.result)
        ElMessage.success('登录成功')
        router.push('/')
      }
    })
  }
  if (!messageChosen.value) {
    // 短信登录
    messageFormRef.value.validate(async valid => {
      if (valid) {
        const res = await loginCodePost(messageForm.value)
        store.setUserInfo(res.data.result)
        ElMessage.success('登录成功')
        router.push('/')
      }
    })
  }
}

// 注册表单
const registerForm = ref({
  account: '',
  password: '',
  mobile: '',
  code: '',
  aggrement: true
})
const registerRules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'change' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 6, max: 24, message: '密码长度在 6 到 24 个字符', trigger: 'change' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'change' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'change' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'change' },
    { min: 6, max: 6, message: '验证码长度为 6 位', trigger: 'change' }
  ],
  aggrement: [{ validator: validateAccept, message: '请阅读并同意协议', trigger: 'change' }]
}
const registerFormRef = ref(null)

// 发送验证码
const sendCode = async () => {
  if (registerShow.value) {
    console.log('我执行了注册发送验证码')
    const res = await registerCode(registerForm.value.mobile)
    console.log('注册发送验证码', res)
  } else {
    console.log('我执行了短信发送验证码')
    const res = await loginCode(messageForm.value.mobile)
    console.log('短信发送验证码', res)
  }
  ElMessage.success('验证码发送成功')
}

// 注册
const registerEvent = async () => {
  const res = await register(registerForm.value)
  console.log('注册', res)
}
const registerSubmit = async () => {
  registerFormRef.value.validate(async valid => {
    if (valid) {
      if (isqqLogin.value) {
        console.log('我是qq注册')
        loginSocialComplement(qqopenId.value, registerForm.value)
      } else {
        console.log('我是普通注册')
        registerEvent()
      }
      // 注册后等待三秒后登录
      setTimeout(() => {
        ElMessage.success('注册成功，正在登录...')
      })
      const res = await login(registerForm.value)
      console.log('登录', res)
      store.setUserInfo(res.data.result)
      router.push('/')
    }
  })
}
</script>

<template>
  <div class="login-page">
    <div class="header">
      <img src="@/assets/icons/logo.svg" alt="" />
      <span class="title">欢迎登录</span>
      <div class="goHome" @click="$router.push('/')">
        <span style="margin: 0px 5px 3px">进入网站首页</span>
        <el-icon style="color: #1d50a3"><DArrowRight /></el-icon>
      </div>
    </div>
    <div class="body">
      <img src="@/assets/icons/login/background.webp" alt="" />
      <div class="container">
        <!-- 控制账号登录或扫码登录 -->
        <div class="nav">
          <div
            :class="{ 'nav__item--active': navChosen, nav__item: !navChosen }"
            @click="toggleModeAccount"
          >
            账户登录
          </div>
          <div
            :class="{ 'nav__item--active': !navChosen, nav__item: navChosen }"
            @click="toggleModeQr"
          >
            扫码登录
          </div>
        </div>
        <!-- 账号登录 -->
        <div class="account" v-if="navChosen">
          <!-- 账号登录 -->
          <div v-if="messageChosen" class="toggle" @click="toggleMode2">
            <el-icon><Message /></el-icon>
            <span>使用短信登录</span>
          </div>
          <div v-if="messageChosen" class="form">
            <el-form :model="accountForm" :rules="accountRules" ref="accountFormRef" size="large">
              <el-form-item prop="account">
                <el-input placeholder="请输入用户名" v-model="accountForm.account">
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input placeholder="请输入密码" show-password v-model="accountForm.password">
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="aggrement">
                <el-checkbox v-model="accountForm.aggrement">
                  我已同意
                  <el-link href="" type="primary">《隐私条款》</el-link>和
                  <el-link href="" type="primary">《服务条款》</el-link>
                </el-checkbox>
              </el-form-item>
            </el-form>
          </div>
          <!-- 短信登录 -->
          <div v-if="!messageChosen" class="toggle" @click="toggleMode2">
            <el-icon><User /></el-icon>
            <span>使用账号登录</span>
          </div>
          <div v-if="!messageChosen" class="form">
            <el-form :model="messageForm" :rules="messageRules" ref="messageFormRef" size="large">
              <el-form-item prop="mobile">
                <el-input placeholder="请输入手机号" v-model="messageForm.mobile">
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code">
                <el-input
                  style="width: 220px"
                  placeholder="请输入验证码"
                  v-model="messageForm.code"
                >
                  <template #prefix>
                    <el-icon><Bell /></el-icon>
                  </template>
                </el-input>
                <div class="sendCode" @click="sendCode">发送验证码</div>
              </el-form-item>
              <el-form-item prop="aggrement">
                <el-checkbox v-model="messageForm.aggrement">
                  我已同意
                  <el-link href="" type="primary">《隐私条款》</el-link>和
                  <el-link href="" type="primary">《服务条款》</el-link>
                </el-checkbox>
              </el-form-item>
            </el-form>
          </div>
          <!-- 提交表单 -->
          <div class="action">
            <el-button class="btn" type="primary" @click="submit">登录</el-button>
          </div>
          <div class="info">
            <a
              class="qqlogin"
              href="https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fconsult-patients.itheima.net%2Flogin%2Fcallback"
            >
              <img style="width: 76px; height: 24px" src="@/assets/icons/login/qq.png" alt="" />
            </a>
            <span style="margin-right: 20px; cursor: pointer">忘记密码</span>
            <span style="cursor: pointer" @click="toggleRegister">免费注册</span>
          </div>
        </div>
        <!-- 扫码登录 -->
        <div class="qrcode" v-if="qrChosen">
          <div class="qrcode__img">
            <img src="@/assets/icons/login/qrCode.jpg" alt="" />
          </div>
          <div class="qrcode__text">
            打开
            <span style="cursor: pointer; color: #1d50a3">Neusoft APP</span>
            扫码登录
          </div>
        </div>
        <!-- 注册 -->
        <div class="register" v-if="registerShow">
          <div class="form">
            <el-form
              :model="registerForm"
              :rules="registerRules"
              ref="registerFormRef"
              size="large"
            >
              <el-form-item prop="account">
                <el-input placeholder="请输入账号" v-model="registerForm.account">
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input placeholder="请输入密码" show-password v-model="registerForm.password">
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="mobile">
                <el-input placeholder="请输入手机号" v-model="registerForm.mobile">
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code">
                <el-input
                  style="width: 220px"
                  placeholder="请输入验证码"
                  v-model="registerForm.code"
                >
                  <template #prefix>
                    <el-icon><Bell /></el-icon>
                  </template>
                </el-input>
                <div class="sendCode" @click="sendCode">发送验证码</div>
              </el-form-item>
              <el-form-item prop="aggrement">
                <el-checkbox v-model="messageForm.aggrement">
                  我已同意
                  <el-link href="" type="primary">《隐私条款》</el-link>和
                  <el-link href="" type="primary">《服务条款》</el-link>
                </el-checkbox>
              </el-form-item>
            </el-form>
            <div class="action">
              <el-button class="btn" type="primary" @click="registerSubmit">注册</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <ul class="links">
        <li class="links__item">关于我们</li>
        <li class="links__item">帮助中心</li>
        <li class="links__item">售后服务</li>
        <li class="links__item">配送与验收</li>
        <li class="links__item">商务合作</li>
        <li class="links__item">搜索推荐</li>
        <li class="links__item" style="border: none">友情链接</li>
      </ul>
      <div>CopyRight © Neusoft</div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-page {
  width: 100%;
  .header {
    width: 100%;
    height: 83px;
    padding: 0px 20px 50px;
    background-color: #fff;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    min-width: 1200px;
    img {
      height: 40px;
      margin-right: 20px;
    }
    .title {
      font-size: 24px;
      color: #666666;
      white-space: nowrap;
    }
    .goHome {
      display: flex;
      align-items: center;
      margin-left: 800px;
      white-space: nowrap;
      cursor: pointer;
      &:hover {
        color: #1d50a3;
      }
    }
  }
  .body {
    width: 100%;
    position: relative;
    img {
      width: 100%;
      height: 488px;
    }
    .container {
      position: absolute;
      top: 60px;
      left: 60%;
      width: 380px;
      background-color: #fff;
      box-shadow: 0 3px 8px rgb(0 0 0 / 20%);
      .nav {
        padding: 20px 0px;
        display: flex;
        justify-content: space-around;
        border: 1px solid #e5e5e5;
        .nav__item {
          font-size: 18px;
          cursor: pointer;
        }
        .nav__item--active {
          font-size: 18px;
          color: #1d50a3;
          cursor: pointer;
        }
      }
      .account {
        width: 380px;
        .toggle {
          width: 100%;
          padding: 15px 0px;
          margin-left: 220px;
          color: #1d50a3;
          display: flex;
          align-items: center;
          cursor: pointer;
        }
        .form {
          width: 300px;
          height: 100px;
          padding: 10px 40px 0px;
          .sendCode {
            flex: 1;
            font-size: 12px;
            text-align: center;
            color: #fff;
            background-color: #409eff;
            border-radius: 3px;
            cursor: pointer;
          }
        }
        .action {
          width: 100%;
          height: 110px;
          margin-top: 50px;
          display: flex;
          flex-direction: column;
          justify-content: space-evenly;
          align-items: center;
          .btn {
            width: 300px;
            height: 45px;
          }
        }
        .info {
          display: flex;
          margin-bottom: 20px;
          color: #666666;
          .qqlogin {
            margin: 0px 100px 0px 30px;
            cursor: pointer;
            img {
              width: 76px;
              height: 24px;
            }
          }
        }
      }
      .qrcode {
        width: 380px;
        display: flex;
        flex-direction: column;
        align-items: center;
        .qrcode__img {
          width: 100%;
          text-align: center;
          img {
            width: 250px;
            height: 250px;
            min-width: 250px;
            margin: 30px 0px 20px;
          }
        }
        .qrcode__text {
          font-size: 16px;
          margin-bottom: 30px;
        }
      }
      .register {
        height: 390px;
        padding: 10px 0px 0px 0px;
        .form {
          width: 300px;
          height: 100px;
          padding: 10px 40px 0px;
          .sendCode {
            flex: 1;
            font-size: 12px;
            text-align: center;
            color: #fff;
            background-color: #409eff;
            border-radius: 3px;
            cursor: pointer;
          }
        }
        .btn {
          width: 300px;
          height: 45px;
        }
      }
    }
  }
  .footer {
    width: 100%;
    height: 80px;
    padding: 30px 0px 50px;
    color: #999999;
    display: flex;
    flex-direction: column;
    align-items: center;
    .links {
      list-style: none;
      display: flex;
      justify-content: center;
      white-space: nowrap;
      .links__item {
        display: flex;
        align-items: center;
        height: 18px;
        font-size: 16px;
        padding: 0px 10px;
        border-right: 1px solid #999999;
        cursor: pointer;
        &:hover {
          color: #1d50a3;
        }
      }
    }
  }
}
</style>
